#include "../mesh.h"
#include "txt.h"

namespace sleek
{
    namespace mesh
    {
        MeshBuffer* LoadMeshFromTxt(core::os::stringc file)
        {
            int     nvert;
            FILE	*filein;
            char	oneline[255];
            float   rx, ry, rz;

            filein = fopen(file.c_str(), "rt");
            if(!filein){ printf("error: couldn't open \"%s\"!\n", file.c_str()); return 0; }

            MeshBuffer *tmp = new MeshBuffer();
            do { fgets(oneline, 255, filein); } while ((oneline[0] == '/') || (oneline[0] == '\n'));
            if(core::os::stringc("Vertices:") != core::os::stringc(oneline).subStr(0,9)) return 0;
            printf("Load mesh: \"%s\"\n", file.c_str());
            sscanf(oneline, "Vertices: %d\n", &nvert);
            tmp->vertices.set_used(nvert);

            for (int i=0;i<nvert;i++)
            {
                do { fgets(oneline, 255, filein); } while ((oneline[0] == '/') || (oneline[0] == '\n'));
                sscanf(oneline, "%f %f %f", &rx, &ry, &rz);
                tmp->vertices[i].Pos = core::math::vector3df(rx,ry,rz);
                tmp->vertices[i].Normal = tmp->vertices[i].Pos.normalise();

                index in;
                    in.vertex[0] = i+0;
                    in.vertex[1] = i+1;
                    in.vertex[2] = i+2;
                tmp->indices.push_back(in);
            }

            fclose(filein);
            tmp->updateNormal();
            return tmp;
        }
        bool WriteMeshToTxt(MeshBuffer *m, core::os::stringc file)
        {
            FILE *out = fopen(file.c_str(), "wb+");
            if(!out){ printf("error: couldn't open \"%s\"!\n", file.c_str()); return 0; }
            printf("Write mesh: \"%s\"\n", file.c_str());
            fprintf(out,"Vertices: %d\n", m->vertices.size());
            for(core::u32 i =0; i<m->vertices.size(); ++i)
                fprintf(out, "%f %f %f\n", m->vertices[i].Pos.x, m->vertices[i].Pos.y, m->vertices[i].Pos.z);
            return 0;
        }
        bool IsMeshFormatTxt(core::os::stringc file)
        {
            FILE	*filein;
            char	oneline[255];
            filein = fopen(file.c_str(), "rt");
            if(!filein){ printf("error: couldn't open \"%s\"!\n", file.c_str()); return 0; }
            do { fgets(oneline, 255, filein); } while ((oneline[0] == '/') || (oneline[0] == '\n'));
            if(core::os::stringc("Vertices:") == core::os::stringc(oneline).subStr(0,9)) return true;
            return false;
        }
    }
}
